package com.test.p01singleton.example06;

import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * 懒汉汉：
 * 优点：线程安全，可以延时加载，如果不使用单例不会
 * 缺点：调用效率不高(加了synchronized)
 */
public class Singleton06 implements Serializable {

    private static Singleton06 singleton;

    private Singleton06(){
        //防止反射漏洞
        if(singleton != null){
            throw new RuntimeException();
        }
    }

    public static synchronized Singleton06 getInstance(){
        if(null == singleton){
            singleton = new Singleton06();
        }
        return singleton;
    }

    /**
     * 防止反序列化漏洞
     * 实际是一种回调
     * @return
     * @throws ObjectStreamException
     */
    private Object readResolve() throws ObjectStreamException{
        return singleton;
    }
}
